<template>
    <div class="xp-component flex-center" @click="open" title="天气">
        <div class="loader loader_bubble" v-if="status===0"></div>
        <div v-else-if="status===1" style="color:#808080">
            加载失败
        </div>
        <div class="full-layout flex-column" v-else>
            <div class="flex-start">
                <div class="xp-location flex-center">
                    {{province}}-{{city}}
                    <el-icon style="margin:2px 0 0 3px"><Position /></el-icon>
                </div>
            </div>
            <div class="flex-between" style="flex: 1;">
                <div class="xp-column-end" style="flex:1">
                    <div class="xp-temp flex-center">
                        <p>{{temp}}°</p>
                    </div>
                    <div class="xp-weather flex-center">
                        <img :src="weathericon">
                        {{weather}}
                    </div>
                    <div class="xp-weather-info">
                        最高{{dayTemp}}° 最低{{nightTemp}}°
                    </div>
                    <div class="xp-weather-info">
                        {{windDirection}}风 湿度{{humidity}}%
                    </div>
                </div>
                <div class="xp-column-end full-h" style="flex:1.5">
                    <ul class="full-layout flex-center" style="height:85%">
                        <li 
                        class="xp-weather-item" 
                        v-for="(item,index) in forecasts" :key="index">
                            <div>
                                {{index===0?'明天':item.week}}
                            </div>
                            <div style="flex:2" class="xp-item-weather">
                                <img :src="item.icon" style="height:30px; width:30px"/>
                                <p>{{item.dayTemp}}°/{{item.nightTemp}}°</p>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="reload-icon" title="刷新">
            <el-icon 
            :class="status===0?'is-loading':''"
            @click.stop="reloadWeather">
                <RefreshRight/>
            </el-icon>
        </div>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, defineComponent, computed, watch, onMounted, getCurrentInstance } from 'vue';
import { useUsersStore } from '@/store/user';
import useLocation from '@/hooks/useLocation';
import { formatWeek } from '@/utils/util';
export default defineComponent({
    name: 'xpWeather',
    components: {},
    props: {
    },
    emits: ['open'],
    setup (props, context) 
    {
        const { proxy }:any = getCurrentInstance();
        const useLocationHooks = useLocation();
        const userStore = useUsersStore();
        let data = reactive({
            options:{
                type:'iframe',
                id:'1001',
                name:'和风天气',
                link:'https://www.qweather.com/weather',
                xIcon:'https://gips0.baidu.com/it/u=1685976296,1188196978&fm=3012&app=3012&autime=1666770119&size=b360,360'
            },
            weatherData:null as any,
            status:0,
            province:'',
            city:'',
            temp:0,
            dayTemp:0,
            nightTemp:0,
            weather:'',
            weathericon:'',
            humidity:'',
            windDirection:'',
            forecasts:[] as any,
            weatherIconList:[
                { weather:'晴', time:'day', icon:require('@/assets/weather/sunny.png') },
                { weather:'晴', time:'night', icon:require('@/assets/weather/night.png') },
                { weather:'多云', time:'day', icon:require('@/assets/weather/cloudy_day.png') },
                { weather:'多云', time:'night', icon:require('@/assets/weather/cloudy_night.png') },
                { weather:'阴', icon:require('@/assets/weather/cloudy.png') },
                { weather:'小雨', icon:require('@/assets/weather/light_rain.png') },
                { weather:'中雨', icon:require('@/assets/weather/moderate_rain.png') },
                { weather:'阵雨', icon:require('@/assets/weather/moderate_rain.png') },
                { weather:'大雨', icon:require('@/assets/weather/heavy_rain.png') },
                { weather:'雷阵雨', icon:require('@/assets/weather/thunderstorm.png') }
            ]
        });
        let methods = {
            open ()
            {
                context.emit('open', data.options);
                console.log(12313);
                
            },
            getWeather ()
            {
                if (proxy.$utils.cache.weather.get()) 
                {
                    data.weatherData = JSON.parse(proxy.$utils.cache.weather.get());
                    data.status = 2;
                    return;
                }
                let AMap = userStore.AMapData;
                let lnglat = proxy.$utils.cache.lnglat.get();
                if (!AMap) 
                {
                    proxy.$message.error('天气数据获取失败');
                    data.status = 1;
                    return;
                }
                let weather = new AMap.Weather();
                let geocoder = new AMap.Geocoder();
                if (!lnglat)
                {
                    console.error('获取定位失败');
                    methods.reloadWeather();
                    return;
                }
                geocoder.getAddress(JSON.parse(lnglat), function (status, result) 
                {
                    if (status === 'complete' && result.info === 'OK') 
                    {
                        let name = result.regeocode.addressComponent.district;
                        methods.getForecast(name, weather);
                        return;
                    }
                    methods.getForecast('北京市', weather);
                    
                });
            },
            async reloadWeather ()
            {
                data.status = 0;
                try
                {
                    await useLocationHooks.getLocalionByIp(userStore.AMapData);
                    methods.getWeather();
                }
                catch (err)
                {
                    console.error(err);
                    data.status = 1;
                    proxy.$message.error('天气数据获取失败');
                }
            },
            getForecast (city, weather)
            {
                weather.getForecast(city, function (err, value) 
                {
                    if (err)
                    {
                        data.status = 1;
                        console.error(err);
                        return;
                    }
                    data.weatherData = value;
                    methods.getLiveWeather(city, weather);
                });
            },
            getLiveWeather (city, weather)
            {
                weather.getLive(city, function (err, value) 
                {
                    if (err)
                    {
                        data.status = 1;
                        console.error(err);
                        return;
                    }
                    Object.assign(data.weatherData, value);
                    proxy.$utils.cache.weather.set(JSON.stringify(data.weatherData));
                    data.status = 2;
                });
            }
        };
        const checkWeather = computed(() => 
        {
            return function (value)
            {
                let date = new Date();
                let weatherArr = null as any;
                let allow = ['晴', '多云'];
                const weatherFilter = (time) => 
                {
                    return data.weatherIconList.filter((item) => 
                    {
                        if (allow.includes(value))
                        {
                            return item.weather === value && item.time === time;
                        }
                        return item.weather === value;
                    });
                };
                if (date.getHours() > 18)
                {
                    weatherArr = weatherFilter('night');
                }
                else
                {
                    weatherArr = weatherFilter('day');
                }
                return weatherArr.length ? weatherArr[0].icon : '';
            };
        });

        const checkForecasets = computed(() => 
        {
            return function (value)
            {
                return value.map((item) => 
                {
                    return {
                        weather:item.dayWeather,
                        dayTemp:item.dayTemp,
                        nightTemp:item.nightTemp,
                        week:formatWeek(item.week),
                        icon:checkWeather.value(item.dayWeather)
                    };
                });
            };
        });

        watch(() => data.weatherData, (newValue) => 
        {
            console.log(newValue);
            if (newValue)
            {
                data.weather = newValue.weather;
                data.province = newValue.province;
                data.city = newValue.city;
                data.temp = newValue.temperature;
                data.dayTemp = newValue.forecasts[0].dayTemp;
                data.nightTemp = newValue.forecasts[0].nightTemp;
                data.humidity = newValue.humidity;
                data.windDirection = newValue.windDirection;
                data.forecasts = checkForecasets.value(newValue.forecasts.slice(1));
                data.weathericon = checkWeather.value(data.weather);
            }
        }, {deep:true});

        onMounted(() => 
        {
            setTimeout(() => 
            {
                methods.getWeather();
            }, 1000);
        });
        
        
        return {
            ...toRefs(data),
            ...methods,
            checkWeather
        };
    }
});
</script>
<style lang='scss' scoped>
.flex-column {
    display: flex;
    flex-direction: column;
}

.xp-column-end {
    @extend .flex-column;
    height: 100%;
    align-items: flex-start;
    justify-content: flex-end;
}
.xp-component {
    width: 100%;
    height: 100%;
    position: relative;
    padding: 11px 10px 11px 20px;

    &:hover {
        .reload-icon {
            display: inline-block;
        }
    }
}

.reload-icon {
    display: none;
    position: absolute;
    top: 10px;
    right: 15px;
    transition: all .3s;
    cursor: pointer;

    &:hover {
        color:$PrimaryColor;
    }
}

.xp-location {
    font-size: .7em;
}

.xp-weather {
    font-size: 1em;
    padding: 3px 0;
    margin-bottom: 5px;

    img {
        height: 1.2em;
        width: 1.2em;
        margin-right: 5px;
    }
}

.xp-temp {
    // font-size: 1em;
    font-size: 2.3em;
    margin-bottom: 5px;
    
    // p {
    //     font-size: 2.3em;
    //     margin-left: 5px;
    //     margin-top: -13px;
    // }
}

.xp-weather-info {
    padding: 2px 0;
    text-align: left;
    font-size: .7em;
}

.xp-weather-item {
    margin: 0px 4px;
    padding: 10px 5px;
    border-radius: 10px;
    height: 100%;
    width: 30%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: .7em;
    background-image: linear-gradient(130deg,#354564 30%,#4c5f7f,#8b9bb8);
    transition: all .3s;
    box-shadow: 0 0 10px 1px rgb(53 69 100);

    // &:hover {
    //     box-shadow: 0 0 10px 1px rgb(53 69 100);
    // }
}

.xp-item-weather {
    display: flex;
    align-items: center;
    align-content: stretch;
    justify-content: flex-end;
    flex-direction: column;
}

.loader {
  position: relative;
  display: block;
  width: 44px;
  height: 44px;
  font-size: 15px;
  box-shadow: 9px 9px 33px #354564, -9px -9px 33px #8b9bb8;
}

.loader::before,
.loader::after {
  content: '';
  position: absolute;
  display: block;
}

.loader_bubble::before {
  top: 10px;
  left: 10px;
  width: 10px;
  height: 10px;
  background: #fff;
  border-radius: 50%;
}

.loader_bubble {
  background: linear-gradient(180deg, rgb(0, 91, 228) 10%, rgb(75, 127, 240) 100%);
  border-radius: 50%;
  transform-origin: 50% 50%;
  animation: bubble7234 1200ms cubic-bezier(0.645, 0.045, 0.355, 1) infinite;
}

@keyframes bubble7234 {
  0% {
    transform: translate3d(0,0,0) rotate(0);
  }

  100% {
    transform: translate3d(0,0,0) rotate(360deg);
  }
}

</style>
